package com.kly.user.task.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kly.user.db.dao.CusomExtDao;
import com.kly.user.db.dao.TStatisticalDao;
import com.kly.user.db.dao.TStatisticalSqlDao;
import com.kly.user.db.entity.TStatisticalSqlEntity;
import com.kly.user.db.entity.UserTaskJobEntity;
import com.kly.user.mybatis.dynamic.MapperService;
import com.kly.user.task.ExecuteHandler;
import com.kly.user.task.ExecuteResult;
import com.kly.user.task.enums.TaskStatusEnum;
import com.kly.user.task.enums.TaskTypeEnum;
import com.kly.user.utils.HttpUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 数据统计
 * @author linqu
 */
@Service("statisticalImpl")
public class StatisticalImpl implements ExecuteHandler {
    private static Log logger = LogFactory.getLog("taskFileLog");
    @Resource
    TStatisticalDao statisticalDao;
    @Resource
    TStatisticalSqlDao statisticalSqlDao;
    @Resource
    MapperService mapperService;
    @NacosValue(value = "${spring.datasource.druid.url}", autoRefreshed = true)
    private String url;
    @NacosValue(value = "${spring.datasource.druid.username}", autoRefreshed = true)
    private String username;
    @NacosValue(value = "${spring.datasource.druid.password}", autoRefreshed = true)
    private String password;
    @Resource
    CusomExtDao cusomExtDao;


    @Override
    public TaskTypeEnum getType() {
        return TaskTypeEnum.STATISTICAL;
    }

    @Override
    public <T> ExecuteResult doExecute(T t) throws Exception {
        // 当前记录数
        AtomicInteger currentIndex = new AtomicInteger(1);

        UserTaskJobEntity entity = (UserTaskJobEntity) t;
        logger.info("Statistical job starting, job detail:{}", JSONObject.toJSONString(entity));
        String driver = "com.mysql.cj.jdbc.Driver";

        Map<String, Object> queryparams = Maps.newHashMap();
        queryparams.put("deleted", 0);
        final List<TStatisticalSqlEntity> statisticalSqlEntities = statisticalSqlDao.selectByParams(queryparams);
        if (CollectionUtils.isEmpty(statisticalSqlEntities)) {
            return ExecuteResult.builder().jobId(entity.getId()).resultMsg("success").resultCode(TaskStatusEnum.SUCCESS.getCode()).taskType(TaskTypeEnum.STATISTICAL.getCode()).build();
        }

        for (TStatisticalSqlEntity statisticalSqlEntity : statisticalSqlEntities) {

            final Date statisticalStartDate = statisticalSqlEntity.getLatestStatisticalDate();
            final Date statisticalEndDate = new Date();
            Map<String, Object> params = Maps.newHashMap();
            params.put("beginDate", statisticalStartDate);
            params.put("endDate", statisticalEndDate);
            final List<Map<String, Object>> resultList = mapperService.execute(statisticalSqlEntity.getSqlText(), params, driver, url, username, password);
            logger.info("statisticalSql result:{},statisticalSql:{},params:{}", resultList,statisticalSqlEntity,params);
            final String sql = statisticalSqlEntity.getSqlText();
//            List<Map<String, Object>> resultList = cusomExtDao.customQuery(sql, params);
            if (CollectionUtils.isEmpty(resultList)) {
                continue;
            }

            for (Map<String, Object> map : resultList) {
                statisticalDao.saveOrUpdate(map);
            }
//            pushDataToAppsFlyer(statisticalSqlEntity.getStatisticalType(), resultList);

            statisticalSqlEntity.setLatestStatisticalDate(statisticalEndDate);
            statisticalSqlDao.updateByPrimaryKey(statisticalSqlEntity);

        }

        final ExecuteResult result = ExecuteResult.builder().jobId(entity.getId()).resultMsg("success").resultCode(TaskStatusEnum.SUCCESS.getCode()).taskType(TaskTypeEnum.STATISTICAL.getCode()).build();
        logger.info("Statistical end, result:{}", JSONObject.toJSONString(result));
        return result;
    }

    private void pushDataToAppsFlyer(Integer statisticalType, List<Map<String, Object>> records) {
        if (CollectionUtils.isEmpty(records)) {
            return;
        }

        String appId = "com.kly.meboo";
        String auth = "RVdnrbmFm9R2fusE3uUidc";
        JSONObject req = new JSONObject();
        JSONObject eventContent = new JSONObject();
        req.put("appsflyer_id", auth);
        req.put("eventCurrency", "USD");
        // 注册用户信息
        if (3 == statisticalType) {
            req.put("eventName", "Registration");
            eventContent.put("fb_mobile_complete_registration", records.parallelStream().mapToLong(o -> (Long)o.get("registe_num")).sum());
        }
        // 建联用户信息
        else if (2 == statisticalType) {
            req.put("eventName", "Connect");
            eventContent.put("Contact", records.parallelStream().mapToLong(o -> (Long)o.get("conact_num")).sum());
        }
        // 有效会话用户信息
        else if (5 == statisticalType) {
            req.put("eventName", "Active_Chat");
            eventContent.put("fb_mobile_tutorial_completion", records.parallelStream().mapToLong(o -> (Long)o.get("effective_chat_num")).sum());
        }
        // 深度会话用户信息
        else if (6 == statisticalType) {
            req.put("eventName", "Deep_Chat");
            eventContent.put("fb_mobile_level_achieved", records.parallelStream().mapToLong(o -> (Long)o.get("deep_chat_num")).sum());
        }
        // 新用户充值信息及收入
        /*else if (10 == statisticalType) {
            req.put("eventName", "D0_Purchase");
            eventContent.put("Subscribe", data);
        }*/
        // 用户充值信息及收入
        /*else if (11 == statisticalType) {
            req.put("eventName", "Purchase");
            eventContent.put("fb_mobile_purchase", data);
        }*/
        req.put("eventValue", eventContent);
        Map<String, String> header = Maps.newConcurrentMap();
        header.put("accept", "application/json");
        header.put("content-type", "application/json");
        header.put("authentication", auth);
        if (statisticalType == 2 || statisticalType == 3 || statisticalType == 5 || statisticalType == 6 || statisticalType == 10 || statisticalType == 11) {
            final String result = HttpUtil.postPageBodyByHttps("https://api2.appsflyer.com/inappevent/"+appId, header, req.toJSONString());
            logger.info("PushDataToAppsFlyerResult, body:{},{}", req.toJSONString(), result);
        }


    }


}
